using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace UILibrary
{
	/// <summary>
	/// Allows serialization and de-serialization of objects into files and strings.
	/// </summary>
	public class psrXmlSerialization
	{
		/// <summary>
		/// Serialize an object into a string.
		/// </summary>
		/// <param name="obj">Object to be serialized.</param>
		/// <returns>String containing XML.</returns>
		public static string SerializeToString(object obj)
		{
			// Serialization of Class into string of xml
			XmlSerializer xmlsSlzr = new XmlSerializer( obj.GetType() );
			StringWriter sw = new StringWriter();
			xmlsSlzr.Serialize( sw, obj );
			return sw.ToString();
		}

		/// <summary>
		/// Serialize the specified object to a file.
		/// </summary>
		/// <param name="obj">Object to be serialized.</param>
		/// <param name="writeFileName">Filename where the object needs to be written.</param>
		public static void SerializeToFile(object obj, string writeFileName)
		{
			// Serialization of Class into string of xml
			XmlSerializer xmlsSlzr = new XmlSerializer( obj.GetType() );
			FileStream fs = new FileStream(writeFileName, FileMode.CreateNew);
			xmlsSlzr.Serialize( fs, obj );
			fs.Close();
		}

		/// <summary>
		/// Deserializes an object from a file and attempts to read back into an object.
		/// </summary>
		/// <param name="readFileName">File which contains the object to be read.</param>
		/// <param name="type">Type of object, use object.GetType().</param>
		/// <returns></returns>
		public static object DeserializeFromFile(string readFileName, Type type)
		{
			// Unserializes instance of class from a file
			XmlSerializer xmlsSlzr = new XmlSerializer( type );
			FileStream fs = new FileStream(readFileName, FileMode.Open);
			object returnval = xmlsSlzr.Deserialize( fs );
			fs.Close();
			return returnval;
		}
	}
}
